class Solution {
public:
    int dp[100005];
    bool flag[100005] = { 0 };
    int ans = 0;
    int numOfMinutes(int n, int headID, vector<int>& manager, vector<int>& informTime) {
        for (int i = 0; i < n; i++) ans = max(ans, dfs(i, manager, informTime, headID));
        return ans;
    }
    int dfs(int pos, vector<int>& manager, vector<int>& informTime, int head)
    {
        if (pos == head) return 0;
        if (flag[pos]) return dp[pos];
        flag[pos] = 1;
        return dp[pos] = dfs(manager[pos], manager, informTime, head) + informTime[manager[pos]];
    }
};